package com.franklin.ideaplugin.api.utils;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorSettings;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.ScrollingModel;

/**
 * @author Franklin
 * @since 2021/9/15 10:28
 */
public class EditorUtils {

    public static void initEditor(Editor editor){
        EditorSettings editorSettings = editor.getSettings();
        // 关闭虚拟空间
        editorSettings.setVirtualSpace(false);
        // 关闭标记位置（断点位置）
        editorSettings.setLineMarkerAreaShown(false);
        // 关闭缩减指南
        editorSettings.setIndentGuidesShown(false);
        // 显示行号
        editorSettings.setLineNumbersShown(true);
        // 支持代码折叠
        editorSettings.setFoldingOutlineShown(true);
        // 附加行，附加列（提高视野）
        editorSettings.setAdditionalColumnsCount(3);
        editorSettings.setAdditionalLinesCount(3);
        // 不显示换行符号
        editorSettings.setCaretRowShown(false);
    }

    /**
     * 平滑移动到指定行
     * @param editor
     * @param lineNumber
     * @param durationMs
     */
    public static void smoothScrollToLine(Editor editor, int lineNumber, int durationMs) {
        if (editor.isDisposed()) {
            return;
        }
        LogicalPosition logicalPosition = new LogicalPosition(lineNumber, 0);
        int targetOffset = editor.logicalPositionToXY(logicalPosition).y;

        ScrollingModel scrollingModel = editor.getScrollingModel();
        int currentOffset = scrollingModel.getVerticalScrollOffset();

        int steps = 10; // 分成 10 步完成
        int stepSize = (targetOffset - currentOffset) / steps;
        int delay = durationMs / steps;

        for (int i = 0; i <= steps; i++) {
            final int offset = currentOffset + stepSize * i;
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            scrollingModel.scrollVertically(offset);
        }
    }

}
